package com.sinaapp.aidaka.server.service;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sinaapp.aidaka.server.dao.UserDao;
import com.sinaapp.aidaka.server.dao.UserInfoDao;
import com.sinaapp.aidaka.server.domain.User;
import com.sinaapp.aidaka.server.utils.MD5Utils;

@Service
public class UserService {

	private static Logger logger = Logger.getLogger(UserService.class);
	
	@Autowired
	private UserDao userDao ;
	
	@Autowired
	private UserInfoDao userInfoDao;
	
	/**
	 * email是否已经被使用
	 * @param email
	 * @return
	 */
	public boolean isEmailExists(String email) {
		return userDao.isUserExists(email);
	}
	
	/**
	 * 判断密码是否正确
	 * @param email
	 * @param password
	 * @return
	 */
	public boolean isPasswordMatch(String email, String password) {
		//password MD5加密
		String md5Password = MD5Utils.getEncodedPassword(password);
		return userDao.isEmailAndPasswordMatch(email, md5Password);
	}
	
	/**
	 * 用户登录
	 * 1. 查询email 和 password（在方法中加密后）是否匹配
	 * 2. 登录，获取用户登录信息
	 * 3. 修改最后登录信息
	 * @param email
	 * @param password
	 * @param lastIP
	 * @return
	 */
	public User login(String email, String password, String lastIP) {
		String md5Password = MD5Utils.getEncodedPassword(password);
		//验证密码和email是否匹配
		if(!userDao.isEmailAndPasswordMatch(email, md5Password)) {
			//邮箱或者密码错误
			return null;
		}
		//登录成功
		User loginUser = userDao.findUserByEmail(email);
		//修改最后登录信息
		userDao.updateUserLoginData(loginUser.getUid(), new Date(), lastIP);
		return loginUser;
	}
	
	/**
	 * 创建新的用户
	 * @param email
	 * @param password
	 */
	public void newUser(String email, String password, String lastIp) {
		String md5Password = MD5Utils.getEncodedPassword(password);
		userDao.saveNewUser(email, md5Password, new Date(), lastIp);
		User user = userDao.findUserByEmail(email);
		userInfoDao.newUserInfo(user.getUid());
	}
	
	/**
	 * 邮箱是否已经激活
	 * @param email
	 * @return
	 */
	public boolean isEmailActived(String email) {
		User user = userDao.findUserByEmail(email);
		return user.isActicate();
	}
		
}
